NextJS, Supabase, 0Auth, and Stripe
The backbone of every SaaS application is a bootstrap that includes a frontend with user sign-ups, a database for user data, and a secure payment pipeline. In this story, we will look at a common and robust setup for your next big project.
In this article, you’ll learn how to build a complete SaaS foundation using:
Step 1: Set Up the Project
First, create a new Supabase project with database.new (Or follow the official Supabase Guide).
Use Supabase with Next.js | Supabase Docs
Learn how to create a Supabase project, add some sample data, and query from a Next.js app.
Create the Next.js Project with the official starter code.
npx create-next-app -e with-supabase
npx create-next-app -e with-supabase
If you already have a Next.js project, you can simply integrate the required auth files into your existing codebase (components, pages and lib/supabase files).
Step 2: Configure Environment Variables
Create a .env.local file in the project root.
API
# https://app.supabase.com/project/_/settings/api
NEXT_PUBLIC_SUPABASE_URL=your-project-url
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-or-anon-key” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
# Update these with your Supabase details from your project settings > API
# https://app.supabase.com/project/_/settings/api
NEXT_PUBLIC_SUPABASE_URL=your-project-url
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-or-anon-key
# Update these with your Supabase details from your project settings > API
# https://app.supabase.com/project/_/settings/api
NEXT_PUBLIC_SUPABASE_URL=your-project-url
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-or-anon-key
You can find the API URL and the publishable key in your Supabase dashboard or with this link.
You can find your secret key in your API Keys Settings or under this link.
Step 3: Install Dependencies
Install the required Supabase packages in your NextJS project:
npm install @supabase/supabase-js @supabase/ssr
npm install @supabase/supabase-js @supabase/ssr
Structure your project like this:
app/authcomponents/authlib/supabase/server
This gives you a clean separation between UI, logic, and server utilities.
Step 4: Cloudflare Turnstile (Bot Protection)
To protect your app from bots, integrate Cloudflare Turnstile.
For this, head over to Cloudflare and either create an account or log in to your existing one.
Then go to Application security > Turnstile and create a new widget.
You can give your widget a meaningful name, add your domain and any subdomains as hostnames, and choose the visibility settings for your widget.
After creating it, you will receive two keys. Add them to your .env.local file.
When testing locally in developement you can use these placeholders.
# Cloudflare
NEXT_PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000AA
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
# Cloudflare
NEXT_PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000AA
TURNSTILE_SECRET_KEY=1x0000000000000000000000000000000AA
Turnstile Wrapper Component
To integrate this, we will use the suggested npm package @marsidev/react-turnstile. This allows us to create a wrapper component that integrates the widget into our app.
<button data-code="npm i @marsidev/react-turnstile
"use client";
import React, { useState, type ReactElement, cloneElement } from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import { encodedRedirect } from "@/utils/encoded-redirect";
type Props = {
children: React.ReactNode;
};
/**
* – Renders Turnstile client-side.
* – If there's exactly one React element child (e.g. your SubmitButton),
* clones it and sets `disabled` / `aria-disabled` until Turnstile returns a token.
*
* Notes:
* – We cast props to `any` when cloning to avoid TypeScript complaints about
* spreading unknown props on the child.
*/
export function CloudFlareWrapper({ children }: Props) {
const [status, setStatus] = useState("");
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY ?? "";
function handleSuccess() {
setStatus("success");
}
// Try to clone a single child and inject disabled props; otherwise render as-is.
let childWithProps: React.ReactNode = children;
try {
const onlyChild = React.Children.only(children) as ReactElement;
if (React.isValidElement(onlyChild)) {
const shouldDisable = status !== "success";
childWithProps = cloneElement(onlyChild, {
disabled: shouldDisable || onlyChild.props.disabled,
"aria-disabled": shouldDisable || onlyChild.props["aria-disabled"],
});
}
} catch {
// Not exactly one child — fall back to rendering children unchanged.
childWithProps = children;
}
return (
{
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification failed"
);
}}
onExpire={() => {
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification expired"
);
}}
onSuccess={() => handleSuccess()}
/>
{/* Feedback while Turnstile is still verifying */}
{!status && (
Checking you're human… {status}
)}
{/* Your button */}
{childWithProps}
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
npm i @marsidev/react-turnstile
"use client";
import React, { useState, type ReactElement, cloneElement } from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import { encodedRedirect } from "@/utils/encoded-redirect";
type Props = {
children: React.ReactNode;
};
/**
* - Renders Turnstile client-side.
* - If there's exactly one React element child (e.g. your SubmitButton),
* clones it and sets `disabled` / `aria-disabled` until Turnstile returns a token.
*
* Notes:
* - We cast props to `any` when cloning to avoid TypeScript complaints about
* spreading unknown props on the child.
*/
export function CloudFlareWrapper({ children }: Props) {
const [status, setStatus] = useState<string>("");
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY ?? "";
function handleSuccess() {
setStatus("success");
}
// Try to clone a single child and inject disabled props; otherwise render as-is.
let childWithProps: React.ReactNode = children;
try {
const onlyChild = React.Children.only(children) as ReactElement<{
disabled?: boolean;
"aria-disabled"?: boolean;
}>;
if (React.isValidElement(onlyChild)) {
const shouldDisable = status !== "success";
childWithProps = cloneElement(onlyChild, {
disabled: shouldDisable || onlyChild.props.disabled,
"aria-disabled": shouldDisable || onlyChild.props["aria-disabled"],
});
}
} catch {
// Not exactly one child — fall back to rendering children unchanged.
childWithProps = children;
}
return (
<div>
<Turnstile
siteKey={siteKey}
options={{
size: "invisible",
}}
onError={() => {
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification failed"
);
}}
onExpire={() => {
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification expired"
);
}}
onSuccess={() => handleSuccess()}
/>
{/* Feedback while Turnstile is still verifying */}
{!status && (
<div className="flex items-center gap-2 text-sm text-gray-500 animate-pulse">
<div className="h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin"></div>
Checking you're human… {status}
</div>
)}
{/* Your button */}
{childWithProps}
</div>
);
}
npm i @marsidev/react-turnstile
"use client";
import React, { useState, type ReactElement, cloneElement } from "react";
import { Turnstile } from "@marsidev/react-turnstile";
import { encodedRedirect } from "@/utils/encoded-redirect";
type Props = {
children: React.ReactNode;
};
/**
* - Renders Turnstile client-side.
* - If there's exactly one React element child (e.g. your SubmitButton),
* clones it and sets `disabled` / `aria-disabled` until Turnstile returns a token.
*
* Notes:
* - We cast props to `any` when cloning to avoid TypeScript complaints about
* spreading unknown props on the child.
*/
export function CloudFlareWrapper({ children }: Props) {
const [status, setStatus] = useState<string>("");
const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY ?? "";
function handleSuccess() {
setStatus("success");
}
// Try to clone a single child and inject disabled props; otherwise render as-is.
let childWithProps: React.ReactNode = children;
try {
const onlyChild = React.Children.only(children) as ReactElement<{
disabled?: boolean;
"aria-disabled"?: boolean;
}>;
if (React.isValidElement(onlyChild)) {
const shouldDisable = status !== "success";
childWithProps = cloneElement(onlyChild, {
disabled: shouldDisable || onlyChild.props.disabled,
"aria-disabled": shouldDisable || onlyChild.props["aria-disabled"],
});
}
} catch {
// Not exactly one child — fall back to rendering children unchanged.
childWithProps = children;
}
return (
<div>
<Turnstile
siteKey={siteKey}
options={{
size: "invisible",
}}
onError={() => {
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification failed"
);
}}
onExpire={() => {
setStatus("error");
return encodedRedirect(
"error",
"/sign-in",
"CloudFlare Verification expired"
);
}}
onSuccess={() => handleSuccess()}
/>
{/* Feedback while Turnstile is still verifying */}
{!status && (
<div className="flex items-center gap-2 text-sm text-gray-500 animate-pulse">
<div className="h-3 w-3 rounded-full border-2 border-gray-400 border-t-transparent animate-spin"></div>
Checking you're human… {status}
</div>
)}
{/* Your button */}
{childWithProps}
</div>
);
}
Next, create a small utility function encoded-redirect.ts:
import { redirect } from "next/navigation";
/**
* Redirects to a specified path with an encoded message as a query parameter.
* @param {('error' | 'success')} type - The type of message, either 'error' or 'success'.
* @param {string} path - The path to redirect to.
* @param {string} message - The message to be encoded and added as a query parameter.
* @returns {never} This function doesn't return as it triggers a redirect.
*/
export function encodedRedirect(
type: "error" | "success",
path: string,
message: string,
) {
return redirect(`${path}?${type}=${encodeURIComponent(message)}`);
}
import { redirect } from "next/navigation";
/**
* Redirects to a specified path with an encoded message as a query parameter.
* @param {('error' | 'success')} type - The type of message, either 'error' or 'success'.
* @param {string} path - The path to redirect to.
* @param {string} message - The message to be encoded and added as a query parameter.
* @returns {never} This function doesn't return as it triggers a redirect.
*/
export function encodedRedirect(
type: "error" | "success",
path: string,
message: string,
) {
return redirect(`${path}?${type}=${encodeURIComponent(message)}`);
}
You can then wrap the auth button with the new wrapper component:
<button data-code="import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { LogoutButton } from "./logout-button";
import { Button } from "@/components/ui/button";
import { CloudFlareWrapper } from "./cloudflare-turnstile-wrapper";
export async function AuthButton() {
const supabase = await createClient();
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
return user ? (
Hey, {user.email}!
) : (
Sign in
Sign up
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { LogoutButton } from "./logout-button";
import { Button } from "@/components/ui/button";
import { CloudFlareWrapper } from "./cloudflare-turnstile-wrapper";
export async function AuthButton() {
const supabase = await createClient();
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
return user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<LogoutButton />
</div>
) : (
<div className="flex gap-2">
<CloudFlareWrapper>
<Button asChild size="sm" variant={"outline"}>
<Link href="/auth/login">Sign in</Link>
</Button>
<Button asChild size="sm" variant={"default"}>
<Link href="/auth/sign-up">Sign up</Link>
</Button>
</CloudFlareWrapper>
</div>
);
}
import Link from "next/link";
import { createClient } from "@/lib/supabase/server";
import { LogoutButton } from "./logout-button";
import { Button } from "@/components/ui/button";
import { CloudFlareWrapper } from "./cloudflare-turnstile-wrapper";
export async function AuthButton() {
const supabase = await createClient();
const { data } = await supabase.auth.getClaims();
const user = data?.claims;
return user ? (
<div className="flex items-center gap-4">
Hey, {user.email}!
<LogoutButton />
</div>
) : (
<div className="flex gap-2">
<CloudFlareWrapper>
<Button asChild size="sm" variant={"outline"}>
<Link href="/auth/login">Sign in</Link>
</Button>
<Button asChild size="sm" variant={"default"}>
<Link href="/auth/sign-up">Sign up</Link>
</Button>
</CloudFlareWrapper>
</div>
);
}
Email Setup
Custom Provider
We can use the integrated Supabase Email Provider, but the free tier is very limited. Because of that, it can be beneficial to use a custom SMTP provider instead.
To do this, you need to update the Email Settings in Supabase using this link. Click on Set up SMTP to open the configurator.
I will be using Resend as my email provider, as it fits seamlessly into the Vercel stack, but you can of course choose any provider you like.
We can then start setting up our domain. For this, head over to Domains and click on + Add Domain****. Follow the setup wizard until Resend provides you with the required DNS records. These need to be added in your domain provider or hosting service.
After adding the DNS records, you need to wait some time depending on your TTL settings. You can monitor the DNS status directly in Resend.
Once everything is set up correctly, you should see the domain verified and be able to create an API key on this page here.
This API key is then used as the password in the custom SMTP settings inside Supabase.
Custom Templates
You can improve how your emails look by using custom HTML templates instead of the default ones.
In your Supabase dashboard, go to Auth Templates, then select the email event you want to edit (for example: signup confirmation).
You can replace the default content with your own HTML. Supabase supports placeholder tags that get replaced automatically, like:
{{ .Email }}{{ .ConfirmationURL }}
Let’s look at an example and change the signup email from looking like this:
to something more recognizable like this:
Update the existing code with a snippet like this:
<button data-code="
Confirm your signup
Confirm your signup
Welcome! Please confirm your email: {{ .Email }}
If you didn’t sign up, you can ignore this email.
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Confirm your signup</title>
</head>
<body style="margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;">
<div style="max-width:500px;margin:auto;background:#fff;padding:30px;border-radius:8px;">
<h2>Confirm your signup</h2>
<p>
Welcome! Please confirm your email: <strong>{{ .Email }}</strong>
</p>
<a href="{{ .ConfirmationURL }}"
style="display:inline-block;margin:20px 0;padding:12px 20px;background:#000;color:#fff;text-decoration:none;border-radius:5px;">
Confirm Email →
</a>
<p style="font-size:12px;color:#777;">
If you didn’t sign up, you can ignore this email.
</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Confirm your signup</title>
</head>
<body style="margin:0;padding:40px;background:#f5f5f5;font-family:Arial,sans-serif;">
<div style="max-width:500px;margin:auto;background:#fff;padding:30px;border-radius:8px;">
<h2>Confirm your signup</h2>
<p>
Welcome! Please confirm your email: <strong>{{ .Email }}</strong>
</p>
<a href="{{ .ConfirmationURL }}"
style="display:inline-block;margin:20px 0;padding:12px 20px;background:#000;color:#fff;text-decoration:none;border-radius:5px;">
Confirm Email →
</a>
<p style="font-size:12px;color:#777;">
If you didn’t sign up, you can ignore this email.
</p>
</div>
</body>
</html>
OAuth
The less friction there is during signup, the more likely users are to create an account. OAuth is a great way to simplify the authentication process, and fortunately, Supabase makes it easy to integrate a wide range of providers.
Before setting up OAuth, update your URL Configuration in Supabase. Until now, your Site URL was probably [https://localhost:3000](https://localhost:3000.).
That worked during development, but OAuth relies on callback URLs, so it’s important to change this to your actual application URL.
Supabase supports many authentication providers. While the setup differs slightly for each one, we’ll use Google as an example since it’s one of the most common choices.
Start by enabling the Google Auth Provider in Supabase.
Next, open the Google Cloud Console and create a new project. Once the project is ready, navigate to APIs & Services
and open the OAuth section.
Fill in the required information, create an OAuth client, and save the generated credentials.
With those credentials available, return to Supabase and paste them into the Google Auth Provider configuration.
The next step is adding an oauth-buttons.tsx component that initiates the OAuth login flow:
<button data-code=""use client";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { useState } from "react";
type OAuthProvider = "google"; // "github" | …
export function OAuthButtons() {
const [loadingProvider, setLoadingProvider] = useState(
null,
);
const handleOAuthLogin = async (provider: OAuthProvider) => {
const supabase = createClient();
setLoadingProvider(provider);
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
alert(error.message);
setLoadingProvider(null);
}
};
return (
handleOAuthLogin("google")}
disabled={loadingProvider !== null}
>
{loadingProvider === "google" ? "Signing in…" : "Google"}
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
"use client";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { useState } from "react";
type OAuthProvider = "google"; // "github" | ...
export function OAuthButtons() {
const [loadingProvider, setLoadingProvider] = useState<OAuthProvider | null>(
null,
);
const handleOAuthLogin = async (provider: OAuthProvider) => {
const supabase = createClient();
setLoadingProvider(provider);
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
alert(error.message);
setLoadingProvider(null);
}
};
return (
<Button
type="button"
variant="outline"
onClick={() => handleOAuthLogin("google")}
disabled={loadingProvider !== null}
>
{loadingProvider === "google" ? "Signing in..." : "Google"}
</Button>
);
}
"use client";
import { createClient } from "@/lib/supabase/client";
import { Button } from "@/components/ui/button";
import { useState } from "react";
type OAuthProvider = "google"; // "github" | ...
export function OAuthButtons() {
const [loadingProvider, setLoadingProvider] = useState<OAuthProvider | null>(
null,
);
const handleOAuthLogin = async (provider: OAuthProvider) => {
const supabase = createClient();
setLoadingProvider(provider);
const { error } = await supabase.auth.signInWithOAuth({
provider,
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
alert(error.message);
setLoadingProvider(null);
}
};
return (
<Button
type="button"
variant="outline"
onClick={() => handleOAuthLogin("google")}
disabled={loadingProvider !== null}
>
{loadingProvider === "google" ? "Signing in..." : "Google"}
</Button>
);
}
Finally, create an auth callback route. This endpoint receives the response from the OAuth provider, exchanges the authorization code for a session, and redirects the user to the appropriate page.
Needs to be the endpoint of the url configuration.
import { createClient } from "@/lib/supabase/server";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const origin = requestUrl.origin;
const token = requestUrl.searchParams.get("token");
const type = requestUrl.searchParams.get("type");
const code = requestUrl.searchParams.get("code");
const redirectTo = requestUrl.searchParams.get("redirect_to");
const next = requestUrl.searchParams.get("next");
const supabase = await createClient();
if (token && type === "recovery") {
return NextResponse.redirect(`${origin}/reset-password?token=${token}`);
}
if (code) {
await supabase.auth.exchangeCodeForSession(code);
}
if (redirectTo && redirectTo.startsWith("/")) {
return NextResponse.redirect(`${origin}${redirectTo}`);
}
if (next && next.startsWith("/")) {
return NextResponse.redirect(`${origin}${next}`);
}
return NextResponse.redirect(`${origin}/dashboard`);
}
import { createClient } from "@/lib/supabase/server";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const requestUrl = new URL(request.url);
const origin = requestUrl.origin;
const token = requestUrl.searchParams.get("token");
const type = requestUrl.searchParams.get("type");
const code = requestUrl.searchParams.get("code");
const redirectTo = requestUrl.searchParams.get("redirect_to");
const next = requestUrl.searchParams.get("next");
const supabase = await createClient();
if (token && type === "recovery") {
return NextResponse.redirect(`${origin}/reset-password?token=${token}`);
}
if (code) {
await supabase.auth.exchangeCodeForSession(code);
}
if (redirectTo && redirectTo.startsWith("/")) {
return NextResponse.redirect(`${origin}${redirectTo}`);
}
if (next && next.startsWith("/")) {
return NextResponse.redirect(`${origin}${next}`);
}
return NextResponse.redirect(`${origin}/dashboard`);
}
Stripe Payments
To accept payments, start by creating a Stripe account or signing in to an existing one. If you haven’t already, create a business account by providing your personal and business information.
Once your account is ready, switch to Sandbox mode. This lets you safely test payments without processing any real transactions.
Next, copy your Publishable Key and Secret Key Secret key into your .env.local file:
# Stripe
NEXT_PUBLIC_STRIPE_PUBLIC_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
# Stripe
NEXT_PUBLIC_STRIPE_PUBLIC_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
The next step is creating a webhook so Stripe can notify your application about payment events.
Create a new webhook endpoint and subscribe it to the these events.
Select the Webhook endpoint option when configuring the destination
and provide the necessary information.
You will receive a Signing Secret, save this till the next step (whsec_xxx).
After that, create a product in the Product Catalog.
Configure its price, billing interval (if applicable), and any other settings your application requires.
When everything is configured, copy the Webhook Signing Secret and the product’s Price ID into your .env.local file:
# Stripe
NEXT_PUBLIC_STRIPE_PUBLIC_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_SIGNING_SECRET=whsec_xxx
STRIPE_PRICE_ID=price_xxx
# Stripe
NEXT_PUBLIC_STRIPE_PUBLIC_KEY=pk_test_xxx
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_SIGNING_SECRET=whsec_xxx
STRIPE_PRICE_ID=price_xxx
To keep track of successful purchases, create a new purchases table in Supabase using the following SQL:
create table public.purchases (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
stripe_checkout_session_id text unique,
stripe_customer_id text,
stripe_payment_intent_id text unique,
stripe_price_id text,
amount_total integer,
currency text,
payment_status text,
purchased_at timestamptz default now(),
created_at timestamptz default now(),
updated_at timestamptz default now()
);
create index purchases_user_id_idx
on public.purchases(user_id);
alter table public.purchases enable row level security;
create policy "Users can view own purchases"
on public.purchases
for select
using (auth.uid() = user_id);
create table public.purchases (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references auth.users(id) on delete cascade,
stripe_checkout_session_id text unique,
stripe_customer_id text,
stripe_payment_intent_id text unique,
stripe_price_id text,
amount_total integer,
currency text,
payment_status text,
purchased_at timestamptz default now(),
created_at timestamptz default now(),
updated_at timestamptz default now()
);
create index purchases_user_id_idx
on public.purchases(user_id);
alter table public.purchases enable row level security;
create policy "Users can view own purchases"
on public.purchases
for select
using (auth.uid() = user_id);
After creating the table, enable the following Row Level Security (RLS) policies to allow users to view their own purchases and permit inserts from your webhook:
create policy "Users can view own purchases"
on public.purchases
for select
using (auth.uid() = user_id);
create policy "Allow inserts into purchases"
on public.purchases
for insert
with check (true);
create policy "Users can view own purchases"
on public.purchases
for select
using (auth.uid() = user_id);
create policy "Allow inserts into purchases"
on public.purchases
for insert
with check (true);
With the database in place, create the Stripe webhook route. This endpoint verifies incoming Stripe events and stores successful purchases in the purchases table.
This needs to match the exact path configured in the Webhook (e.g. /app/api/stripe/webhook/route.ts)
import Stripe from "stripe";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { createClient } from "@/lib/supabase/client";
const webhookSecret = process.env.STRIPE_SIGNING_SECRET!;
const supabase = createClient();
export async function POST(req: Request) {
const body = await req.text();
const signature = (await headers()).get("stripe-signature");
if (!signature) {
return new NextResponse("Missing stripe signature", {
status: 400,
});
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
} catch (err) {
console.error("Webhook signature verification failed", err);
return new NextResponse("Invalid signature", {
status: 400,
});
}
try {
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as Stripe.Checkout.Session;
const userId = session.metadata?.supabase_user_id;
if (!userId) {
throw new Error("Missing supabase user id");
}
const result = await supabase.from("purchases").insert({
user_id: userId,
stripe_checkout_session_id: session.id,
stripe_customer_id:
typeof session.customer === "string" ? session.customer : null,
stripe_payment_intent_id:
typeof session.payment_intent === "string"
? session.payment_intent
: null,
stripe_price_id: session.metadata?.stripe_price_id ?? null,
amount_total: session.amount_total,
currency: session.currency,
payment_status: session.payment_status,
purchased_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
});
if (result.error) {
throw result.error;
}
break;
}
default:
console.log(`Unhandled event type: ${event.type}`);
}
return NextResponse.json({
received: true,
});
} catch (err) {
console.error("Webhook handler failed:", err);
return new NextResponse("Webhook handler failed", {
status: 500,
});
}
}
import Stripe from "stripe";
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
import { createClient } from "@/lib/supabase/client";
const webhookSecret = process.env.STRIPE_SIGNING_SECRET!;
const supabase = createClient();
export async function POST(req: Request) {
const body = await req.text();
const signature = (await headers()).get("stripe-signature");
if (!signature) {
return new NextResponse("Missing stripe signature", {
status: 400,
});
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
} catch (err) {
console.error("Webhook signature verification failed", err);
return new NextResponse("Invalid signature", {
status: 400,
});
}
try {
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as Stripe.Checkout.Session;
const userId = session.metadata?.supabase_user_id;
if (!userId) {
throw new Error("Missing supabase user id");
}
const result = await supabase.from("purchases").insert({
user_id: userId,
stripe_checkout_session_id: session.id,
stripe_customer_id:
typeof session.customer === "string" ? session.customer : null,
stripe_payment_intent_id:
typeof session.payment_intent === "string"
? session.payment_intent
: null,
stripe_price_id: session.metadata?.stripe_price_id ?? null,
amount_total: session.amount_total,
currency: session.currency,
payment_status: session.payment_status,
purchased_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
});
if (result.error) {
throw result.error;
}
break;
}
default:
console.log(`Unhandled event type: ${event.type}`);
}
return NextResponse.json({
received: true,
});
} catch (err) {
console.error("Webhook handler failed:", err);
return new NextResponse("Webhook handler failed", {
status: 500,
});
}
}
Next, add a checkout route that creates a Stripe Checkout Session and redirects users to Stripe’s hosted payment page.
(e.g. /app/api/stripe/checkout/route.ts)
import { NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
export async function POST(req: Request) {
try {
const body = await req.json();
const priceId = process.env.STRIPE_PRICE_ID;
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
if (!priceId) {
throw new Error("Missing STRIPE_PRICE_ID");
}
if (!siteUrl) {
throw new Error("Missing NEXT_PUBLIC_SITE_URL");
}
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: `${siteUrl}/dashboard`,
cancel_url: `${siteUrl}/pricing`,
customer_email: body.email,
metadata: {
supabase_user_id: body.userId,
stripe_price_id: priceId,
},
});
return NextResponse.json({
url: session.url,
});
} catch (err) {
console.error("Stripe checkout creation failed:", err);
return NextResponse.json(
{
error: err instanceof Error ? err.message : "Checkout failed",
},
{ status: 500 },
);
}
}
import { NextResponse } from "next/server";
import { stripe } from "@/lib/stripe";
export async function POST(req: Request) {
try {
const body = await req.json();
const priceId = process.env.STRIPE_PRICE_ID;
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL;
if (!priceId) {
throw new Error("Missing STRIPE_PRICE_ID");
}
if (!siteUrl) {
throw new Error("Missing NEXT_PUBLIC_SITE_URL");
}
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: [
{
price: priceId,
quantity: 1,
},
],
success_url: `${siteUrl}/dashboard`,
cancel_url: `${siteUrl}/pricing`,
customer_email: body.email,
metadata: {
supabase_user_id: body.userId,
stripe_price_id: priceId,
},
});
return NextResponse.json({
url: session.url,
});
} catch (err) {
console.error("Stripe checkout creation failed:", err);
return NextResponse.json(
{
error: err instanceof Error ? err.message : "Checkout failed",
},
{ status: 500 },
);
}
}
Before testing the payment flow, we need a simple pricing page that allows users to start the checkout process.
<button data-code="import PricingTable from "@/components/pricing-table";
import { createClient } from "@/lib/supabase/server";
export default async function PricingPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
return (
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
import PricingTable from "@/components/pricing-table";
import { createClient } from "@/lib/supabase/server";
export default async function PricingPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
return (
<div className="min-h-screen">
<div className="max-w-4xl mx-auto py-20 px-6">
<PricingTable user={user} />
</div>
</div>
);
}
import PricingTable from "@/components/pricing-table";
import { createClient } from "@/lib/supabase/server";
export default async function PricingPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
return (
<div className="min-h-screen">
<div className="max-w-4xl mx-auto py-20 px-6">
<PricingTable user={user} />
</div>
</div>
);
}
This retrieves the user server side.
The following component displays a pricing card and calls the checkout route we created earlier.
{
if (!user) return;
setLoading(true);
const res = await fetch("/api/stripe/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: user.id,
email: user.email,
}),
});
const { url } = await res.json();
window.location.href = url;
};
return (
Pro Plan
$39.99
One-time payment
-
{features.map((f) => (
-
{f}
))}
{loading ? "Loading…" : "Buy Now"}
);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
"use client";
import { useState } from "react";
import { User } from "@supabase/supabase-js";
import { Check } from "lucide-react";
const features = [
"Unlimited access to all features",
"Future updates included",
"One-time payment",
];
export default function PricingTable({ user }: { user: User | null }) {
const [loading, setLoading] = useState(false);
const handleCheckout = async () => {
if (!user) return;
setLoading(true);
const res = await fetch("/api/stripe/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: user.id,
email: user.email,
}),
});
const { url } = await res.json();
window.location.href = url;
};
return (
<div className="border rounded-2xl p-8 max-w-md mx-auto bg-white dark:bg-zinc-900">
<h2 className="text-xl font-bold mb-2">Pro Plan</h2>
<p className="text-4xl font-bold mb-1">$39.99</p>
<p className="text-sm text-zinc-500 mb-6">One-time payment</p>
<ul className="space-y-2 mb-6">
{features.map((f) => (
<li key={f} className="flex items-center gap-2 text-sm">
<Check size={16} />
{f}
</li>
))}
</ul>
<button
onClick={handleCheckout}
disabled={loading}
className="w-full bg-black text-white py-2 rounded-lg disabled:opacity-50"
>
{loading ? "Loading..." : "Buy Now"}
</button>
</div>
);
}
"use client";
import { useState } from "react";
import { User } from "@supabase/supabase-js";
import { Check } from "lucide-react";
const features = [
"Unlimited access to all features",
"Future updates included",
"One-time payment",
];
export default function PricingTable({ user }: { user: User | null }) {
const [loading, setLoading] = useState(false);
const handleCheckout = async () => {
if (!user) return;
setLoading(true);
const res = await fetch("/api/stripe/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: user.id,
email: user.email,
}),
});
const { url } = await res.json();
window.location.href = url;
};
return (
<div className="border rounded-2xl p-8 max-w-md mx-auto bg-white dark:bg-zinc-900">
<h2 className="text-xl font-bold mb-2">Pro Plan</h2>
<p className="text-4xl font-bold mb-1">$39.99</p>
<p className="text-sm text-zinc-500 mb-6">One-time payment</p>
<ul className="space-y-2 mb-6">
{features.map((f) => (
<li key={f} className="flex items-center gap-2 text-sm">
<Check size={16} />
{f}
</li>
))}
</ul>
<button
onClick={handleCheckout}
disabled={loading}
className="w-full bg-black text-white py-2 rounded-lg disabled:opacity-50"
>
{loading ? "Loading..." : "Buy Now"}
</button>
</div>
);
}
Testing the Application
To test everything locally, use the Stripe CLI to forward webhook events to your application.
Once it’s running, copy the generated Signing Secret into your .env.local file.
stripe listen --forward-to localhost:3000/api/stripe/webhook
stripe listen --forward-to localhost:3000/api/stripe/webhook


